package update

import (
	"context"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 设置当前时间
func Currentdate(mongo *mongo.Database, ctx context.Context) {
	filter := bson.M{"$currentDate": bson.M{"update": true, "updateDate": bson.M{"$type": "date"}, "updateTimestamp": bson.M{"$type": "timestamp"}}}
	mongo.Collection("test").UpdateOne(ctx, bson.M{}, filter)
}

// 指定时间设置
func Date2(mongo *mongo.Database, ctx context.Context) {
	timeLayout := "2006-01-02 15:04:05"
	tempdate, _ := time.Parse(timeLayout, "2022-07-01 16:07:00")
	filter := bson.M{"$set": bson.M{"update": tempdate}}
	mongo.Collection("test").UpdateOne(ctx, bson.M{}, filter)
}

// 指定时间戳形式更新
func Date3(mongo *mongo.Database, ctx context.Context) {
	tempDate := primitive.Timestamp{T: uint32(time.Now().Unix()), I: 1}
	filter := bson.M{"$set": bson.M{"updateTimestamp": tempDate}}
	mongo.Collection("test").UpdateOne(ctx, bson.M{}, filter)
}

// 给指定字段增加指定值，可以为负数，如果该字段不存在，则会以该值为初始值创建字段，$mul则是乘法
func Inc(mongo *mongo.Database, ctx context.Context) {
	filter := bson.M{"$inc": bson.M{"object.id": -2}}
	mongo.Collection("test").UpdateOne(ctx, bson.M{}, filter)
}

// 如果指定的值小于字段的当前值，则将字段的值更新为指定的值，max关键字则反过来
func Min(mongo *mongo.Database, ctx context.Context) {
	filter := bson.M{"$min": bson.M{"object.id": -3}}
	// 也可以用与日期格式
	// timeLayout := "2006-01-02 15:04:05"
	// tempdate, _ := time.Parse(timeLayout, "2021-07-01 16:07:00")
	// filter := bson.M{"$min": bson.M{"date": tempdate}}
	mongo.Collection("test").UpdateOne(ctx, bson.M{}, filter)
}

// 字段重命名
func Rename(mongo *mongo.Database, ctx context.Context) {
	filter := bson.M{"$rename": bson.M{"object.id": "object.id1", "date": "date1"}}
	mongo.Collection("test").UpdateOne(ctx, bson.M{}, filter)
}

// 当set形式导致新增文档时，setOnInsert内的字段会被作为其中一个字段插入文档中
func SetOnInsert(mongo *mongo.Database, ctx context.Context) {
	findFilter := bson.M{"_id": -1}
	filter := bson.M{"$set": bson.M{"newObject": "新增文档"}, "$setOnInsert": bson.M{"text": "只有新增文档时才会新建该字段2"}}
	upsert := true
	options := options.UpdateOptions{Upsert: &upsert}
	_, err := mongo.Collection("test").UpdateOne(ctx, findFilter, filter, &options)
	fmt.Println(err)
}
